package com.tc.dispatch.web.schedule.order;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;
import java.util.*;
import net.sf.json.JSONObject;

import com.tc.dispatch.web.aaservice.AAHelper;
import com.tc.dispatch.web.controller.UserState;
import com.tc.dispatch.web.gsservice.gsHelper;
import com.tc.dispatch.aa.ejb.AA_DPServiceLocal;
import com.tc.dispatch.aa.exception.AAException;
import com.tc.dispatch.gsalgorithm.spec.parse;
import com.tc.dispatch.gsalgorithm.spec.spec;
import com.tc.dispatch.gsservice.action.GSCalcAction;
import com.tc.dispatch.gsservice.action.GSCalcActionImp;
import com.tc.dispatch.gsservice.basic.common.tcdate;
import com.tc.dispatch.gsservice.ejb.GSServiceLocal;
import com.tc.dispatch.gsservice.exception.*;
import net.sf.json.JSONArray;

import com.tc.dispatch.web.util.FloatJsonValueProcessor;
import com.tc.dispatch.web.util.WidgtFactory;
import com.tc.dispatch.web.util.tools;
import com.tc.dispatch.gsservice.model.GSConstants;
import com.tc.dispatch.gsservice.model.OrderSumMain;
import com.tc.dispatch.gsservice.model.OrderSumSub;
import com.tc.dispatch.gsservice.model.OtherConstants;
import com.tc.dispatch.gsservice.model.OutProcess;
import com.tc.dispatch.gsservice.model.ProcessFlow;
import com.tc.dispatch.gsservice.model.ProcessStep;

import org.apache.commons.beanutils.BeanUtils;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

import net.sf.json.JsonConfig;
import com.tc.dispatch.web.util.DateJsonValueProcessor;
import com.tc.dispatch.web.util.check.CheckValid;

/**
 * <p>
 * Title: tcweb
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: Copyright (c) 2007
 * </p>
 * <p>
 * Company: zju
 * </p>
 *
 * @author jackyjia
 * @version 1.0
 */

public class orderSumMain extends HttpServlet {
	private static final String CONTENT_TYPE = "text/html; charset=utf-8";
	private UserState us = null;

	// Initialize global variables
	public void init() throws ServletException {
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType(CONTENT_TYPE);
		// response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();

		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		HttpSession sess = request.getSession();

		CheckValid rcv = WidgtFactory.getRequestCheckValid(request);
		CheckValid scv = WidgtFactory.getSimpleCheckValid();
		String action = (String) rcv.checkString("action");
		if (action.equals("list")) {
			Integer page = (Integer) rcv.checkInteger("start");
			
			Integer pagePerNum = (Integer) rcv.checkInteger("limit",10);
			String id = (String) rcv.checkString("id");
			
			try {
				List ret;
				String whereStr = "";
				if (id != null && !id.equals(""))
					ret = gss.findOrderSumMain(" where id=" + id + "");

				else {
					String specType = (String) rcv.checkString("specType");
					String scheme = (String) rcv.checkString("scheme");
					String month1 = (String) rcv.checkString("month1");
					String year1 = (String) rcv.checkString("year1");
					String type = (String) rcv.checkString("type");
					String spec = (String) rcv.checkString("spec");
					if (!scheme.equals(""))
						scheme = " processscheme=" + scheme + " and ";
					
					//如果所有的数据都是空的
					if(specType.equals("")&&month1.equals("")&&scheme.equals("")&&year1.equals("")&&type.equals("")&&spec.equals(""))
					{
						//从session中读取数据。
						if (sess.getAttribute("ordersummain_month1") != null) {
							month1 = (String) sess.getAttribute("ordersummain_month1");
							month1 = " month1=" + month1 + " and ";
						}
						
						if (sess.getAttribute("ordersummain_year1") != null) {
							year1 = (String) sess.getAttribute("ordersummain_year1");
							year1 = " year1=" + year1 + " and ";
						}
						
						if (sess.getAttribute("ordersummain_type") != null) {
							type = (String) sess.getAttribute("ordersummain_type");
							sess.setAttribute("type", type);
						}
						if (sess.getAttribute("ordersummain_spec") != null) {
							spec = (String) sess.getAttribute("ordersummain_spec");
							spec = (" spec='" + spec + "' and ");
						}
						if (sess.getAttribute("ordersummain_specType") != null) {
							specType = (String) sess.getAttribute("ordersummain_specType");
							specType = " specType='" + specType + "' and ";
						}
						
					}
					else
					{
					if (!month1.equals("")) {
						sess.setAttribute("ordersummain_month1", month1);
						month1 = " month1=" + month1 + " and ";
					}
					if (!year1.equals("")) {
						sess.setAttribute("ordersummain_year1", year1);
						year1 = " year1=" + year1 + " and ";
					}
					if (!type.equals("")) {
						sess.setAttribute("ordersummain_type", type);
						type = " ordersummain_type =" + type + " and";
						
					}
					if (!spec.equals("")) {
						sess.setAttribute("ordersummain_spec", spec);
						spec = (" spec='" + spec + "' and ");
						
					}
					if (!specType.equals("")) {
						sess.setAttribute("ordersummain_specType", specType);
						specType = " specType='" + specType + "' and ";
						
					}
					}
					System.out.println("specType:"+specType);
					whereStr = "( " + spec + scheme + specType + type + month1
							+ year1 + " 1=1)";
					ret = gss.findOrderSumMainByPagesWhere(page.intValue(), pagePerNum.intValue(),
							whereStr);
					whereStr = " where " + whereStr;

				}

				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.lang.Float.class,
						new FloatJsonValueProcessor());

				// BeanUtils.copyProperties();

				json.put("totalProperty", new Integer(gss
						.getOSMTotalNum(whereStr)));
				JSONArray arr = JSONArray.fromObject(ret.toArray(), cfg);
				json.put("root", arr);
				response.getWriter().print(json);
			} catch (GSException e) {
				System.out.println("list error:" + e.getMessage());
				out.print("{success:false, data:'false'}");
			}
		} else if (action.equals("new")) {
			Integer id = (Integer) scv.checkInteger(null);
			try {
				String spec = (String) rcv.checkString("spec");
				Integer factory = (Integer) rcv.checkInteger("factory");
				String transnum = (String) rcv.checkString("transnum");
				Integer ordernum = (Integer) rcv.checkInteger("ordernum");
				String ssign = (String) rcv.checkString("ssign");
				String ssign_yz = (String) rcv.checkString("ssign_yz");
				Float grossweight = (Float) rcv.checkFloat("grossweight");
				Float qiandao_yield = (Float) rcv.checkFloat("qiandao_yield");
				Float yimo = (Float) rcv.checkFloat("yimo");
				Float weimo = (Float) rcv.checkFloat("weimo");
				Float feipin = (Float) rcv.checkFloat("feipin");
				Float qiandao_cost = (Float) rcv.checkFloat("qiandao_cost");
				Float product_cost_before = (Float) rcv
						.checkFloat("product_cost_before");
				String specType = (String) rcv.checkString("specType");
				Integer processScheme = (Integer) rcv
						.checkInteger("processScheme");
				String plate = (String) rcv.checkString("plate");
				Float baozhuangfei = (Float) rcv.checkFloat("baozhuangfei");
				Float houdao_yield = (Float) rcv.checkFloat("houdao_yield");
				Float product_cost_last = (Float) rcv
						.checkFloat("product_cost_last");
				java.util.Date date1 = tools.stringToDate(request
						.getParameter("date1"));
				Float ordercost = (Float) rcv.checkFloat("ordercost");
				Float lirun = (Float) rcv.checkFloat("lirun");
				String bz = (String) rcv.checkString("bz");
				String maker = (String) rcv.checkString("maker");
				java.util.Date makeDate = tools.stringToDate(request
						.getParameter("makeDate"));
				byte type = Byte.parseByte(request.getParameter("type"));
				Float peifang = (Float) rcv.checkFloat("peifang");
				String spec_yz = (String) rcv.checkString("spec_yz");
				Integer month1 = (Integer) rcv.checkInteger("month1");
				Integer year1 = (Integer) rcv.checkInteger("year1");

				OrderSumMain osm = new OrderSumMain(id, spec, factory,
						transnum, ordernum, ssign, ssign_yz, peifang, spec_yz,
						grossweight, qiandao_yield, yimo, weimo, feipin,
						qiandao_cost, product_cost_before, specType,
						processScheme, plate, baozhuangfei, houdao_yield,
						product_cost_last, date1, ordercost, lirun, type, bz,
						maker, makeDate, month1, year1);
				gss.createOrderSumMain(osm);
			} catch (NumberFormatException nfe) {
				System.out.print("numberfomat error!:" + nfe.getMessage());
			} catch (GSException gse) {
				System.out.println("list error:" + gse.getMessage());
				out.print("{success:false, data:'false'}");
			}
			response.getWriter().print("{success:true}");

		} else if (action.equals("update")) {

			try {
				Integer id = (Integer) rcv.checkInteger("id");
				String spec = (String) rcv.checkString("spec");
				Integer factory = (Integer) rcv.checkInteger("factory");
				String transnum = (String) rcv.checkString("transnum");
				Integer ordernum = (Integer) rcv.checkInteger("ordernum");
				String ssign = (String) rcv.checkString("ssign");
				String ssign_yz = (String) rcv.checkString("ssign_yz");
				Float grossweight = (Float) rcv.checkFloat("grossweight");
				Float qiandao_yield = (Float) rcv.checkFloat("qiandao_yield");
				Float yimo = (Float) rcv.checkFloat("yimo");
				Float weimo = (Float) rcv.checkFloat("weimo");
				Float feipin = (Float) rcv.checkFloat("feipin");
				Float qiandao_cost = (Float) rcv.checkFloat("qiandao_cost");
				Float product_cost_before = (Float) rcv
						.checkFloat("product_cost_before");
				String specType = (String) rcv.checkString("specType");
				Integer processScheme = (Integer) rcv
						.checkInteger("processScheme");
				String plate = (String) rcv.checkString("plate");
				Float baozhuangfei = (Float) rcv.checkFloat("baozhuangfei");
				Float houdao_yield = (Float) rcv.checkFloat("houdao_yield");
				Float product_cost_last = (Float) rcv
						.checkFloat("product_cost_last");
				java.util.Date date1 = tools.stringToDate(request
						.getParameter("date1"));
				Float ordercost = (Float) rcv.checkFloat("ordercost");
				Float lirun = (Float) rcv.checkFloat("lirun");
				String bz = (String) rcv.checkString("bz");
				String maker = (String) rcv.checkString("maker");
				java.util.Date makeDate = tools.stringToDate(request
						.getParameter("makeDate"));
				byte type = Byte.parseByte(request.getParameter("type"));
				Float peifang = (Float) rcv.checkFloat("peifang");
				String spec_yz = (String) rcv.checkString("spec_yz");
				Integer month1 = (Integer) rcv.checkInteger("month1");
				Integer year1 = (Integer) rcv.checkInteger("year1");
				// byte type = (byte) (type_s.equals("目标") ? 0 : 1);
				OrderSumMain osm = new OrderSumMain(id, spec, factory,
						transnum, ordernum, ssign, ssign_yz, peifang, spec_yz,
						grossweight, qiandao_yield, yimo, weimo, feipin,
						qiandao_cost, product_cost_before, specType,
						processScheme, plate, baozhuangfei, houdao_yield,
						product_cost_last, date1, ordercost, lirun, type, bz,
						maker, makeDate, month1, year1);
				gss.updateOrderSumMain(osm);
			} catch (NumberFormatException nfe) {
				System.out.print("numberfomat error!:" + nfe.getMessage());
			} catch (GSException gse) {
				System.out.println("update error:" + gse.getMessage());
				out.print("{success:false, data:'false'}");
			}
			response.getWriter().print("{success:true}");

		}

	}

	public boolean removeOSM(int id) {
		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		try {
			gss.removeOrderSumMain(id);
		} catch (GSException gse) {
			System.out.println("removeOSM error :" + gse.getMessage());
			return false;
		}
		return true;

	}

	public boolean updateRecord(OrderSumMain osm) {

		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		try {
			gss.updateOrderSumMain(osm);
		} catch (GSException gse) {
			System.out.println("updateRecord error :" + gse.getMessage());
			return false;
		}
		return true;
	}

	public int createOrderSumMain(OrderSumMain osm) {
		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		AA_DPServiceLocal aa = AAHelper.getAA_DPServiceLocal();
		if (us == null) {
			WebContext webContext = WebContextFactory.get();
			HttpSession session = webContext.getSession();
			us = (UserState) session.getValue("userState");
		}
		int ret = 0;
		try {
			// 需要设置，year1,month1
			List feeList = gss.findOtherConstants(" where name='"
					+ GSConstants.FEE + "'");
			Float fee = new Float(1);
			if (feeList.size() > 0)
				fee = ((OtherConstants) feeList.get(0)).getConstant();
			System.out.println(fee);
			osm.setYear1(new Integer(tcdate.getYear(osm.getDate1())));
			osm.setMonth1(new Integer(tcdate.getMonth(osm.getDate1())));
			osm.setSpecType(parse.parseSpec(osm.getSpec()).sort());
			ProcessFlow pf = gss.getFlow(osm.getSpec());
			osm.setSpecType(pf.getSpecType());
			osm.setProcessScheme(new Integer(pf.getSchemeId()));
			osm.setSsign_yz(osm.getSsign());
			osm.setSpec_yz(osm.getSpec());
			osm.setMaker(aa.getUser(us.getUserId()).getUsername());
			osm.setMakeDate(new Date());
			osm.setOrdercost(new Float(osm.getOrdercost().floatValue()
					/ fee.floatValue()));
			System.out.println("maker is:" + osm.getMaker() + "::orderCost:"
					+ osm.getOrdercost().floatValue());

			ret = gss.createOrderSumMain(osm);
		} catch (GSException gse) {
			System.out.println("createOrderSumMain error :" + gse.getMessage());
			return 0;
		} catch (AAException ae) {
			System.out.println("AAexception:" + ae.getMessage());
			return 0;
		}
		return ret;

	}

	public List readKaiMo(OrderSumMain osm) {
		GSServiceLocal gss = gsHelper.getGSServiceLocal();

		try {
			return gss.getErpKaiMoList(osm.getTransnum());
		} catch (GSException gse) {
			System.out.println("readKaiMo error :" + gse.getMessage());
			return null;
		}

	}

	public boolean createOSS(OrderSumMain osm) {
		GSServiceLocal gss = gsHelper.getGSServiceLocal();

		/*
		 * 1，先找到加工流程约束。 2,根据这个流程创建默认的加工流程。
		 */
		try {
			// ProcessFlow pf = gss.getFlow(osm.getSpec());
			List psList = gss.findProcessStep(" where specName='"
					+ osm.getSpecType() + "' and scheme="
					+ osm.getProcessScheme());
			Iterator it = psList.iterator();
			List subList = new ArrayList();
			GSCalcAction gsca = gss.getGSCalc();
			spec before = parse.parseSpec(osm.getSpec_yz());
			//OutProcess op = gss.getKnife(before.sort(), before);
			while (it.hasNext()) {
				ProcessStep ps = (ProcessStep) it.next();
				OrderSumSub oss = new OrderSumSub();
				oss.setOrderSumId(osm.getId());
				oss.setProcessName(ps.getProcessName());
				oss.setProcessPos(new Integer(ps.getProcessPos()));
				oss.setAfterSpec(osm.getSpec());
				oss.setProcessYield(new Float(1));
				oss.setProcessUpdate(new Float(1));
				oss.setType(osm.getType());

				gss.createOrderSumSub(oss);
			}
		} catch (GSException gse) {
			System.out.println("createOSS error :" + gse.getMessage());
			return false;
		}
		return true;

	}

	public List getFinishedList(String ssign, String spec, String plate,
			Date date1) {
		Date dateF = tcdate.getStartFromDate(date1);
		Date dateT = tcdate.getEndFromDate(date1);

		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		AA_DPServiceLocal aadp = AAHelper.getAA_DPServiceLocal();

		try {

			return gss.getFinishedPro(ssign, spec, plate, dateF, dateT);
		} catch (GSException gse) {
			System.out.println("getFinishedList error :" + gse.getMessage());
			return null;
		}

	}

	public List getScheme(String spec) {
		GSServiceLocal gss = gsHelper.getGSServiceLocal();

		try {
			spec m_spec = parse.parseSpec(spec);

			return gss.findProcessStep(" where specName='" + m_spec.sort()
					+ "' order by processPos");
		} catch (GSException gse) {
			System.out.println("getScheme error :" + gse.getMessage());
			return null;
		}

	}

	public List getLikeSpec(String workflow, String map, String spec) {
		GSServiceLocal gss = gsHelper.getGSServiceLocal();

		try {

			return gss.findLikeSpec(workflow, map, spec);
		} catch (GSException gse) {
			System.out.println("getLikeSpec error :" + gse.getMessage());
			return null;
		}

	}

	public List getFactoryBySpec(String ssign, String spec) {
		GSServiceLocal gss = gsHelper.getGSServiceLocal();

		try {

			return gss.getFactoryBySpec(ssign + "\\" + spec);
		} catch (GSException gse) {
			System.out.println("getFactoryBySpec error :" + gse.getMessage());
			return null;
		}

	}
	
	public int findIdByInf(String ssign,String spec,int year1,int month1,String type)
	{
		
		GSServiceLocal gss = gsHelper.getGSServiceLocal();

		try {
			String whereStr=" where ssign='"+ssign+"' and spec='"+spec+"' and year1="+year1+" and month1="+month1+" and type="+type;
			List ret =gss.findOrderSumMain(whereStr);
			if(ret.size()>0)
				return ((OrderSumMain)ret.get(0)).getId().intValue();
			else
				return 0;
		} catch (GSException gse) {
			System.out.println("findIdByInf error :" + gse.getMessage());
			return 0;
		}
	}

	// Clean up resources
	public void destroy() {
	}
}